<!-- subpkg_consult/payment/index.vue -->
<script lang="ts" setup>
import { postPatientConsultOrderAPI, postPatientConsultPayApi } from '@/apis/consult'
import { getPatientListAPI } from '@/apis/patient'
import { preOrderAPI } from '@/apis/payment'
import { useConsultStore } from '@/stores/consult'
import type { PatientItem } from '@/types/patient'
import type { OrderPreData } from '@/types/payment'
import { onLoad } from '@dcloudio/uni-app'
import { onMounted, ref } from 'vue'

const orderPreInfo = ref({} as OrderPreData)
const store = useConsultStore()
const createPreOrder = async () => {
  const res = await preOrderAPI({
    type: store.type,
    illnessType: store.illnessType,
  })
  console.log(res)
  orderPreInfo.value = res.data
}
onLoad(() => {
  createPreOrder()
  getPatientInfo()
})
const patientInfo = ref<PatientItem>()
const getPatientInfo = async () => {
  const res = await getPatientListAPI(store.patientId)
  console.log('患者信息', res)

  patientInfo.value = res.data
}
const orderId = ref('')
const handlePay = async () => {
  if (orderId.value) {
    return uni.showToast({
      title: '订单已存在,不能重复创建',
      icon: 'none',
    })
  }

  const res = await postPatientConsultOrderAPI({
    type: Number(store.type),
    illnessType: Number(store.illnessType),
    patientId: store.patientId,
    depId: store.depId,
    illnessDesc: store.illnessInfo1.illnessDesc,
    illnessTime: store.illnessInfo1.illnessTime,
    consultFlag: store.illnessInfo1.consultFlag,
    pictures: store.illnessInfo1.pictures,
  })
  console.log('立即支付', res)
  orderId.value = res.data.id
  // store.reset()
  customPaymentRef.value?.open?.()
}
// 4. 自定义支付弹窗
const customPaymentRef = ref<UniHelper.UniPopupInstance>()

onMounted(() => {
  // 检查暴露出来的方法
  console.log('暴露出来的方法', customPaymentRef.value)
})

const handleClose = async () => {
  const res = await uni.showModal({
    title: '关闭支付',
    content: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelText: '仍要退出',
    cancelColor: '#848484',
    confirmText: '继续支付',
    confirmColor: '#16C2A3',
  })
  if (res.cancel) {
    customPaymentRef.value?.close?.()
  }
}
const handleConfirm = async (index: number) => {
  if (index === 0) {
    uni.showToast({
      title: '微信支付暂不支持',
      icon: 'none',
    })
    //#ifdef MP-WEIXIN
    // 本质还是发送网络请求，获取后端返回的参数
    // 调用微信支付的 API (SDK方法)
    //wx.requestPayment(传入后端返回的支付参数)
    //#endif
  } else if (index === 1) {
    //#ifndef MP-WEIXIN
    const res = await postPatientConsultPayApi({
      orderId: orderId.value,
      paymentMethod: '1',
      payCallback: 'http://localhost:5173/#/subpkg_consult/pages/room/room',
    })
    location.href = res.data.payUrl
    //#endif
  }
}
const handleChange = (index: number) => {
  console.log('支付方式', index)
}
</script>

<template>
  <scroll-page>
    <view class="payment-page">
      <uni-section
        title-font-size="32rpx"
        title-color="#121826"
        padding="30rpx"
        :title="`图文问诊 ${orderPreInfo.payment ?? '--'} 元`"
      >
        <uni-list :border="false">
          <uni-list-item
            title="极速问诊"
            note="自动分配医生"
            thumb="/static/uploads/doctor-avatar.jpg"
            thumb-size="lg"
          />
          <uni-list-item
            title="优惠券"
            show-arrow
            :right-text="`-¥${orderPreInfo.couponDeduction ?? '--'}.00`"
          />
          <uni-list-item title="积分抵扣">
            <template #footer>
              <view class="uni-list-text-red">-¥{{ orderPreInfo.pointDeduction ?? '--' }}.00</view>
            </template>
          </uni-list-item>
          <uni-list-item title="实付款">
            <template #footer>
              <view class="uni-list-text-red">¥{{ orderPreInfo.actualPayment ?? '--' }}.00</view>
            </template>
          </uni-list-item>
        </uni-list>
      </uni-section>

      <view class="dividing-line"></view>

      <uni-section title-font-size="32rpx" title-color="#121826" padding="30rpx" title="患者资料">
        <uni-list :border="false">
          <uni-list-item title="患者信息">
            <template #footer>
              <view class="uni-list-text-gray">
                {{ patientInfo?.name ?? '--' }} | {{ patientInfo?.genderValue ?? '--' }} |
                {{ patientInfo?.age ?? '--' }}岁
              </view>
            </template>
          </uni-list-item>
          <uni-list-item border title="病情描述" :note="store.illnessInfo1.illnessDesc" />
        </uni-list>
      </uni-section>

      <view class="payment-agreement">
        <radio color="#20c6b2" value="1" />
        我已同意<text style="color: #20c6b2">支付协议</text>
      </view>
    </view>
    <!-- 下一步操作 -->
    <view class="next-step">
      <view class="total-amount">
        合计: <text class="number">¥{{ orderPreInfo.actualPayment }}.00</text>
      </view>
      <button class="uni-button" @click="handlePay">立即支付</button>
    </view>
    <custom-payment
      ref="customPaymentRef"
      :amount="orderPreInfo?.payment"
      :order-id="orderId"
      v-if="orderPreInfo?.payment"
      @close="handleClose"
      @change="handleChange"
      @confirm="handleConfirm"
    />
  </scroll-page>
</template>

<style lang="scss">
@import './index.scss';
</style>
